package com.me.service;

import com.me.annotation.Inject;
import com.me.dao.DbContext;
import com.me.dao.db.DbSet;
import com.me.model.Goods;
import com.me.model.Recommend;

import java.util.Collection;

public class GoodsService {
    private DbSet<Goods> goods;
    private DbSet<Recommend> rec;

	@Inject
    public GoodsService(DbContext ctx) {
        this.goods = ctx.getGoods();
        this.rec = ctx.getRecommends();
    }

    public Collection<Goods> getByType(String type,int page,int size) {
        return goods.findLike("typeid",type,page,size);
    }

    public Collection<Goods> getByRec(String type,int page,int size) {
        int iType;
        if (type.equals("hot")) {
            iType = 2;
        } else if (type.equals("new")){
            iType = 3;
        }else{
            iType = 0;
        }
        Collection<Goods> glist = goods.contact(rec).addConstrain("goods.id","recommend.goodsid").
		        findAll("recommend.type", String.format("%d",iType));
        return glist;
    }

	public Collection<Goods> getAllForPage(int page, int size) {
		return goods.findAll(null, page, size);
	}

    public String getName(String type) {
        if (type.equals("hot")) {
            return "热销";
        } else if (type.equals("new")) {

            return "新品";
        }
        return "参数错误";
    }

    public Collection<Goods> getByKey(String key, int page, int size) {
        return goods.findLike("name",String.format("%%%s%%",key), page, size);
    }

    public Goods getById(String id) {
        return goods.find("id",id);

    }

	public void update(Goods g) {
		goods.update(g, "id", g.getId());
		goods.save();
	}

	public void add(Goods g) {
		goods.add(g);
		goods.save();
	}
}
